package com.ljf.sso;

import com.ljf.framework.context.LjfContextManager;
import com.ljf.framework.exception.LjfException;
import com.ljf.framework.filter.LjfAbstractFilter;
import com.ljf.framework.filter.LjfFilter;
import com.ljf.framework.filter.LjfFilterAuthStrategy;
import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;
import com.ljf.framework.result.JsonResultEnum;
import com.ljf.framework.security.token.LjfTokenManager;
import com.ljf.framework.security.token.LjfTokenConstants;

import java.util.Arrays;
import java.util.List;

/**
 * 说明：sso

 * @Auther: lijinfeng
 * @Date: 2024/4/15
 */
public class SsoFilter extends LjfAbstractFilter implements LjfFilter {
    LjfLogService log = LjfLogManager.getLogger(SsoFilter.class);

    @Override
    public List<String> getIncludeList() {
        return Arrays.asList("/sso/auth");
    }


    @Override
    public LjfFilterAuthStrategy getAuthStrategy() {
        return r -> {
            if (!SsoManager.getServerConfig().open)
                return true;
            log.info("SSO第三方应用获取token");
            //获得token
            String appId = LjfContextManager.getRequest().getParam(SsoConstants.APP_ID);
            String appSc = LjfContextManager.getRequest().getParam(SsoConstants.APP_SC);
            //客制化校验秘钥
            Long apply = SsoManager.getSsoHandler().ssoHandler.apply(appId, appSc);
            if (apply == 0L)
                throw new LjfException(JsonResultEnum.ACCESS_UNAUTHORIZED, "");

            String token = LjfTokenManager.createToken(apply);
            LjfContextManager.getResponse().addHeader(LjfTokenConstants.TOKEN_NAME, token);
            LjfTokenManager.saveTokenValue(token);
            log.info("SSO第三方应用" + appId + "获取到了token:" + token);
            return false;
        };
    }

    /**
     * 处理逻辑
     */
    public boolean doCusFilter() {
            return true;

    }


    @Override
    public Integer getOrder() {
        return 20;
    }
}
